<?php

namespace App\Admin\Actions\Grid\Withdraw;

use App\Models\UserWithdraw;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Grid\RowAction;
use Dcat\Admin\Traits\HasPermissions;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class WithdrawStateGrid extends RowAction
{
    /**
     * @return string
     */
    protected $title = '提现';
    public $input = [];

    public function setInput($input)
    {
        $this->input = $input;
        switch ($input['status']) {
            case TRADE_STATUS_SUCCESS:
                $this->title = "成功";
                break;
            case TRADE_STATUS_FAIL:
                $this->title = "失败";
                break;
        }
    }

    public function getConfirmContent()
    {
        $arr = [
            TRADE_STATUS_SUCCESS => "提现成功",
            TRADE_STATUS_FAIL => "提现失败",
        ];

        return $arr[$this->input['status']] ?? "确认操作";
    }

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $data = $request->all();
        /**
         * $@var $withdraw UserWithdraw
         */
        $withdraw = UserWithdraw::query()->where('id', $this->getKey())->first();
        if (!$withdraw) {
            return $this->fail();
        }

        $res = false;
        switch ($data['status']) {
            case TRADE_STATUS_SUCCESS:
                $res = $withdraw->success();
                break;
            case TRADE_STATUS_FAIL:
                $res = $withdraw->fail();
                break;
        }

        return $res ? $this->success() : $this->fail();
    }

    public function success()
    {
        return $this->response()
            ->success('操作成功: ' . $this->getKey())
            ->redirect('/user-withdraw');
    }

    public function fail()
    {
        return $this->response()
            ->error('操作失败: ' . $this->getKey())
            ->redirect('/user-withdraw');
    }

    /**
     * @return string|array|void
     */
    public function confirm()
    {
        return [$this->getConfirmContent(), '弹窗内容'];
    }

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }

    /**
     * @return array
     */
    protected function parameters()
    {
        return [
            'status' => $this->input['status']
        ];
    }

}
